from fdfs_client.client import Fdfs_client

from django.conf import settings
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework import status
from goods.models import SPU, Brand, GoodsCategory
from meiduo_admin.spu.spu_serializers import SPUSerializer, GoodsBrandSerializer, GoodCategorySerialier
from meiduo_admin.user.my_pagination import MyNumberPagination


class SPUModelViewSet(ModelViewSet):
    pagination_class = MyNumberPagination
    queryset = SPU.objects.all()
    serializer_class = SPUSerializer


class GoodBrandView(ListAPIView):
    pagination_class = None
    queryset = Brand.objects.all()
    serializer_class = GoodsBrandSerializer


# 新增SPU获取一级分类
class GoodCategoryView(ListAPIView):
    pagination_class = None
    queryset = GoodsCategory.objects.filter(parent=None).all()
    serializer_class = GoodCategorySerialier


# 新增SPU获取二级三级分类
class GoodCategorytwothreeView(ListAPIView):
    pagination_class = None
    serializer_class = GoodCategorySerialier

    def get_queryset(self):
        cat_id = self.kwargs["cat_id"]
        cat = GoodsCategory.objects.filter(parent=cat_id).all()
        return cat


# 上传图片
class GoodImageView(APIView):
    def post(self, request):
        image = request.FILES.get("image")

        if not image:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        client = Fdfs_client(settings.FDDS_CIENT)  # 上传
        result = client.upload_by_buffer(image.read())
        # 判断是否上传成功
        if result["Status"] != "Upload successed.":
            return Response(status=status.HTTP_400_BAD_REQUEST)

        img_url = settings.BASE_URL + result["Remote file_id"]

        return Response({"img_url": img_url})
        # request.FILE

